import Foundation
import TunnelKitCore
import TunnelKitOpenVPN

private func makeConfig() -> OpenVPN.ProviderConfiguration? {
    // 获取文件路径
    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let configFilePath = documentsDirectory.appendingPathComponent("connected_config.ovpn")
    
    // 检查文件是否存在
    guard FileManager.default.fileExists(atPath: configFilePath.path) else {
        print("Config file does not exist")
        return nil
    }
    
    do {
        // 读取文件内容为字符串
        let configFileContent = try String(contentsOf: configFilePath, encoding: .utf8)
        
        // 将文件内容转换为 Data 对象
        guard let configData = configFileContent.data(using: .utf8) else {
            print("Failed to convert config file content to Data")
            return nil
        }
        
        // 使用 OpenVPN 的配置解析器解析文件内容
        let builder = try OpenVPN.ConfigurationParser.parsed(from: configData)
        let cfg = builder.configuration
        
        // 创建配置对象
        var providerConfiguration = OpenVPN.ProviderConfiguration("YoYoVPN", appGroup: "123231", configuration: cfg)
        providerConfiguration.shouldDebug = true
        providerConfiguration.masksPrivateData = false
        return providerConfiguration
        
    } catch {
        print("Error reading config file: \(error.localizedDescription)")
        return nil
    }
}

private func connect() {
    guard let cfg = makeConfig() else { return }
    AppEvenType.HomeVPN.connectPrepare()
    Task {
        let extra = NetworkExtensionExtra()
        try await vpn.reconnect(
            AppConfig.tunnel_id,
            configuration: cfg,
            extra: extra,
            after: .seconds(2)
        )
    }
}

private func disconnect() {
    AppEvenType.HomeVPN.connectPrepare()
    Task {
        await vpn.disconnect()
    }
}
